<template>
  <div class="users">
    <HeaderNav></HeaderNav>
    <div class="content">
      <div class="search-bar">
        <input type="text" placeholder="搜索用户名称" v-model="searchQuery">
        <button class="add-button" @click="openAddModal">添加用户</button>
      </div>
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th class="name-column">用户名称</th>
              <th class="price-column">用户密码</th>
              <th class="quantity-column">真实姓名</th>
              <th class="image-column">邮箱</th>
              <th class="image-column">电话号码</th>
              <th class="image-column">身份</th>
              <th class="action-column">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredUsers" :key="item.userid">
              <td class="name-column">{{ item.username }}</td>
              <td class="price-column">{{ item.pwd }}</td>
              <td class="quantity-column">{{ item.truename }}</td>
              <td class="image-column">{{ item.cardid }}</td>
              <td class="image-column">{{ item.phone }}</td>
              <td class="image-column">{{ item.role }}</td>
              <td class="action-column">
                <button class="edit-button" @click="openEditModal(item)">编辑</button>
                <button class="del-button" @click="confirmDelete(item.userid)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <h2>编辑用户信息</h2>
        <form @submit.prevent="saveUser">
          <div class="form-group">
            <label>用户名称</label>
            <input v-model="editingUser.username" type="text" required>
          </div>
          <div class="form-group">
            <label>用户密码</label>
            <input v-model="editingUser.pwd" type="password" required>
          </div>
          <div class="form-group">
            <label>真实姓名</label>
            <input v-model="editingUser.truename" type="text">
          </div>
          <div class="form-group">
            <label>身份证号</label>
            <input v-model="editingUser.cardid" type="text">
          </div>
          <div class="form-group">
            <label>电话号码</label>
            <input v-model="editingUser.phone" type="tel">
          </div>
          <div class="form-group">
            <label>身份</label>
            <select v-model="editingUser.role">
              <option value="root">root</option>
              <option value="user">user</option>
            </select>
          </div>
          <div class="form-actions">
            <button type="button" @click="closeEditModal" class="cancel-button">取消</button>
            <button type="submit" class="save-button">保存</button>
          </div>
        </form>
      </div>
    </div>

    
    <!-- 添加用户模态框 -->
<div v-if="showAddModal" class="modal-overlay">
  <div class="modal-content">
    <h2>添加新用户</h2>
    <form @submit.prevent="adduser">
      <div class="form-group">
        <label>用户名称</label>
        <input v-model="newuser.username" type="text" required>
      </div>
      <div class="form-group">
        <label>用户密码</label>
         <input v-model="newuser.pwd" type="number">
      </div>
      <div class="form-group">
        <label>真实姓名</label>
        <input v-model="newuser.truename" type="text">
      </div>
      <div class="form-group">
        <label>身份证号</label>
        <input v-model="newuser.cardid" type="number">
      </div>
      <div class="form-group">
        <label>电话号码</label>
        <input v-model="newuser.phone" type="tel">
      </div>
       <div class="form-group">
            <label>身份</label>
            <select v-model="newuser.role">
              <option value="root">root</option>
              <option value="user">user</option>
            </select>
          </div>
      <div class="form-actions">
        <button type="button" @click="closeAddModal" class="cancel-button">取消</button>
        <button type="submit" class="save-button">保存</button>
      </div>
    </form>
  </div>
  </div>
  </div>
</template>

<script setup>
import axios from '../../api/axios';
import HeaderNav from '@/views/admin/HeaderNav.vue';
import { useRoute } from 'vue-router'
import { ref, computed } from 'vue'

const route = useRoute()
const use = ref([])
const loading = ref(true)
const searchQuery = ref('')
const showEditModal = ref(false)
const editingUser = ref({
  userid: '',
  username: '',
  pwd: '',
  truename: '',
  cardid: '',
  phone: '',
  role: ''
})

const showAddModal = ref(false);
const selectedFile = ref(null);
const newuser = ref({
  username: '',
  pwd: '',
  truename: '',
  cardid: '',
  phone: '',
  role: ''
});

// 打开添加模态框
const openAddModal = () => {
  newuser.value = {
    username: '',
    pwd: '',
    truename: '',
    cardid: '',
    phone: '',
    role: '',
  };
  selectedFile.value = null;
  showAddModal.value = true;
};

// 关闭添加模态框
const closeAddModal = () => {
  showAddModal.value = false;
  selectedFile.value = null;
};

// 添加用户
const adduser = async () => {
    const payload = {
      username: newuser.value.username,
      pwd: newuser.value.pwd,
      truename: newuser.value.truename,
      cardid: Number(newuser.value.cardid),
      phone: Number(newuser.value.phone),
      role: newuser.value.role
    };

    const response = await axios.post('/api/users/adduser', payload);
    if (response.data.code === 200) {
      alert('添加成功');
      fetchUsers();
      closeAddModal();
    } else {
      alert('添加失败: ' + (response.data.msg || '未知错误'));
  } 
};

   // 获取用户列表
const fetchUsers = () => {
  axios.post('/api/users/use').then((res) => {
    if (res.data.code === 200) {
      use.value = res.data.user;
    }
  }).catch((err) => {
    console.error("请求失败:", err);
  });
}

fetchUsers();

// 搜索过滤
const filteredUsers = computed(() => {
  return use.value.filter(user => 
    user.username.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    user.truename.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    user.phone.includes(searchQuery.value)
  )
})

// 打开编辑模态框
const openEditModal = (user) => {
  editingUser.value = { ...user }
  showEditModal.value = true
}

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false
}

// 保存用户信息
const saveUser = () => {
  console.log("正在提交的数据:", editingUser.value); // 正确的日志位置
  
  axios.post('/api/users/updateuser', editingUser.value)
    .then(res => {
      if (res.data.code === 200) {
        alert('用户信息更新成功');
        fetchUsers();
        closeEditModal();
      } else {
        alert('更新失败: ' + (res.data.msg || '未知错误'));
      }
    })
    .catch(err => {
      console.error("请求失败:", err);
      alert('更新失败，请检查控制台');
    });
}

// 确认删除
const confirmDelete = (userid) => {
  if(confirm('确定要删除这个用户吗？')) {
    deleteuser(userid);
  }
};

// 删除用户
const deleteuser = async (userid) => {
  try {
    const response = await axios.post('/api/users/deluser', { userid });
    if (response.data.code === 200) {
      alert('删除成功');
      fetchUsers(); 
    } else {
      alert('删除失败: ' + (response.data.msg || '未知错误'));
    }
  } catch (err) {
    console.error("删除失败:", err);
    alert('删除失败，请检查控制台');
  }
};
</script>

<style scoped>
.users {
  display: flex;
  font-family: 'Arial', sans-serif;
}

.content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

input {
  width: 30%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 10px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1160px;
}

.data-table th,
.data-table td {
  text-align: left;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

.data-table th {
  background-color: #f2f2f2;
}

.data-table tr:hover {
  background-color: #f5f5f5;
}

.name-column {
  width: 15%;
}

.price-column,
.quantity-column,
.image-column {
  width: 15%;
}

.action-column {
  width: 10%;
}

.edit-button {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  background-color: #007BFF;
  color: #fff;
  cursor: pointer;
}

.edit-button:hover {
  background-color: #0056b3;
}

 /* 删除按钮 */
.del-button {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  background-color: #dc3545;
  color: #fff;
  cursor: pointer;
}

.del-button:hover {
  background-color: #c82333;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-button {
  padding: 8px 16px;
  margin-right: 10px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button {
  padding: 8px 16px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.save-button:hover {
  background-color: #0056b3;
}


.image-preview {
  max-width: 100px;
  max-height: 100px;
  margin-top: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: block;
}

.form-group input[type="file"] {
  padding: 5px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-button {
  padding: 10px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.add-button:hover {
  background-color: #218838;
}
</style>